package com.mediacloud.app.newsmodule.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.basenews.TextViewTarget;
import com.mediacloud.app.newsmodule.utils.NewsTypeTitle;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;

import org.apache.commons.lang3.ArrayUtils;

import java.text.DecimalFormat;

/**
 * Copyright (c) 2021 唐小陆 All rights reserved.
 * author：txl
 * date：2021/3/11
 * description：资讯列表底部那一排统一处理
 */
public class NewsItemBottomLinearLayout extends LinearLayout {
    /**
     * 资讯类型
     */
    private TextView tvNewsType;
    /**
     * 这个线和资讯一起显示隐藏
     */
    private View line;
    /**
     * 资讯来源
     */
    private TextView tvNewsSource;
    /**
     * 发布时间
     */
    private TextView tvNewsPublishData;
    /**
     * 阅读量
     */
    private TextView tvNewsReadCount;
    /**
     * 阅读量的容器
     */
    private View hitContainer;
    /**
     * 评论或者互动
     */
    private TextView tvNewsComment;

    protected int[] sizeArr;
    protected int size;
    protected TextViewTarget textViewTarget;

    public NewsItemBottomLinearLayout(Context context) {
        this(context, null);
    }

    public NewsItemBottomLinearLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NewsItemBottomLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.HORIZONTAL);
        size = getContext().getResources().getDimensionPixelSize(R.dimen.dimen12);
        sizeArr = new int[]{size, size};
        loadViews(context);
    }

    private void loadViews(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.aappfactory_itemliststyle_news_bottom, this, true);
        tvNewsType = view.findViewById(R.id.newsType);
        int color = AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getMainColor();
        tvNewsType.setTextColor(color);
        line = view.findViewById(R.id.viewLine);
        tvNewsSource = view.findViewById(R.id.newsReferNameLabel);
        tvNewsPublishData = view.findViewById(R.id.newsPubdate);
        hitContainer = view.findViewById(R.id.hitStubLeft);
        tvNewsReadCount = view.findViewById(R.id.newsHitCountLabel);
        tvNewsComment = view.findViewById(R.id.newsCommentLabel);
    }

    /**
     * 统一处理资讯的底部，
     */
    public void handleArticle(ArticleItem articleItem) {
        dealNewsType(articleItem);
        dealSource(articleItem);
        dealPublishData(articleItem);
        dealReadCount(articleItem);
        dealComment(articleItem);
    }

    /**
     * 处理阅读量
     */
    private void dealReadCount(ArticleItem item) {
        if (item.mShowSwitch != null && item.mShowSwitch.allowShowHitCount && item.getShowreadingcountflag() == 1) {
            tvNewsReadCount.setText(item.getHitCount() + "");
            hitContainer.setVisibility(View.VISIBLE);
        } else {
            hitContainer.setVisibility(View.GONE);
        }
    }

    /**
     * 处理发布时间
     */
    private void dealPublishData(ArticleItem item) {
        // 发布时间
        if (/*!TextUtils.isEmpty(item.getPublishdate()) &&*/ item.mShowSwitch != null && item.mShowSwitch.allowShowPublishDate) {
            tvNewsPublishData.setVisibility(View.VISIBLE);
            tvNewsPublishData.setText(item.getPublishdate_format());//DateParse.newsdays(item.getPublishdate(), "yyyy-MM-dd HH:mm:ss", view.getContext()));
        } else {
            tvNewsPublishData.setVisibility(View.GONE);
        }
    }

    /**
     * 处理来源
     */
    private void dealSource(ArticleItem item) {
        if (!TextUtils.isEmpty(item.getReferName()) && item.mShowSwitch != null && item.mShowSwitch.allowShowSource) {
            tvNewsSource.setVisibility(View.VISIBLE);
            boolean isRound = AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).isRound();
            //  isRound =false;
            tvNewsSource.setCompoundDrawablesRelative(null, null, null, null);
            //圆巴巴
            if (isRound && URLUtil.isNetworkUrl(item.getSourceImage())) {
                if (textViewTarget == null) {
                    textViewTarget = new TextViewTarget(tvNewsSource, sizeArr, TextViewTarget.DrawableDirection.START);
                }
                String imgUrl;
                imgUrl = item.getSourceImage();
              //  GlideUtils.loadUrl(imgUrl, getContext(), textViewTarget, sizeArr, null, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), false, false, null);
               /* RequestOptions options = new RequestOptions().override(sizeArr[0],sizeArr[1]);
                FunKt.load(textViewTarget,imgUrl,options);*/
                RequestOptions options = new RequestOptions()
                        .placeholder(AppFactoryGlobalConfig.getDefaultImageLoadDrawable())
                        .error(AppFactoryGlobalConfig.getDefaultImageLoadDrawable())
                        .override(sizeArr[0],sizeArr[1]);
                Glide.with(getContext()).asDrawable().apply(options).into(textViewTarget);
                tvNewsSource.setText(" " + item.getReferName());//胎神说显示不完rmatLongChar(item.getReferName()));
            } else
                tvNewsSource.setText(item.getReferName());//formatLongChar(item.getReferName()));
        } else {
            tvNewsSource.setVisibility(View.GONE);
        }
    }


    private void dealNewsType(ArticleItem articleItem) {
        switch (articleItem.getType()) {
            case TypeX.NEWS.LIVE_VIDEO: {
                tvNewsType.setVisibility(View.VISIBLE);
                line.setVisibility(View.VISIBLE);
                tvNewsType.setText("电视直播");
                break;
            }
            case TypeX.NEWS.LIVE_AUDIO: {
                tvNewsType.setVisibility(View.VISIBLE);
                line.setVisibility(View.VISIBLE);
                tvNewsType.setText("广播直播");
                break;
            }
            default: {
                tvNewsType.setVisibility(View.GONE);
                line.setVisibility(View.GONE);
                break;
            }
        }
//        setNewsTypeMarkAndBordColor(articleItem,tvNewsType);
    }

    ShapeDrawable shapeDrawable;

    /**
     * 还有个样子 比那个优先级还高
     *
     * @param textView
     * @return
     */
    public final boolean generateNewsTypeBg(TextView textView) {
        boolean isRound = AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).isRound();
        if (!isRound)
            return false;
        int color = AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getMainColor();
        if (color == Color.WHITE) {
            try {
                color = Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getContent_show_top_color());
            } catch (Exception e) {
                color = Color.GRAY;
            }
        }
        textView.setTextColor(Color.WHITE);
        if (shapeDrawable == null) {
            int size = getContext().getResources().getDimensionPixelSize(R.dimen.defaultloading_roundradius);
            shapeDrawable = generateRoundShapeDrawable(size, color);
        }
        textView.setBackground(shapeDrawable);
        return true;
    }

    protected ShapeDrawable generateRoundShapeDrawable(int size, int color) {
        float[] outerRadii = {size, size, size, size, size, size, size, size};
        RoundRectShape roundRectShape = new RoundRectShape(outerRadii, null, null);
        ShapeDrawable drawable = new ShapeDrawable(roundRectShape);
        int lr = getResources().getDimensionPixelOffset(R.dimen.dimen3);
        drawable.setPadding(lr, 0, lr, 0);

        drawable.getPaint().setColor(color);
        drawable.getPaint().setStyle(Paint.Style.FILL);
        return drawable;
    }

    protected void setNewsTypeMarkAndBordColor(ArticleItem item, TextView newsTypeLabel) {
        if (item.isFromTop) {
            newsTypeLabel.setVisibility(View.VISIBLE);
            newsTypeLabel.setTextColor(DefaultBgUtil.getTintColor(getContext()));
            if (shapeDrawable == null) {
                int size = getContext().getResources().getDimensionPixelSize(R.dimen.defaultloading_roundradius);
                shapeDrawable = generateRoundShapeDrawable(size, Color.parseColor("#ffffff"));
            }
            newsTypeLabel.setBackground(shapeDrawable);
            newsTypeLabel.setText("置顶");
            return;
        }

        if (!needSetNewsTagLabel(item.getType()) || AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).isopen_list_icon == 0) {
            newsTypeLabel.setVisibility(View.GONE);
            return;
        }
        newsTypeLabel.setVisibility(View.VISIBLE);
        if (item.getCustomColumns() != null
                && !TextUtils.isEmpty(item.getCustomColumns().getListTag())
                && !newsTypeLabel.getResources().getString(R.string.default_tag).equals(item.getCustomColumns().getListTag())) {
            newsTypeLabel.setText(item.getCustomColumns().getListTag());
        } else {
            newsTypeLabel.setText(NewsTypeTitle.newstypetitle(item.getType(), newsTypeLabel.getContext()));
            if ("爆料".equals(newsTypeLabel.getText())) {
                if (!TextUtils.isEmpty(item.getReferCatalogName())) {
                    if (item.getReferCatalogName().length() > 4) {
                        newsTypeLabel.setText(item.getReferCatalogName().substring(0, 4));
                    } else {
                        newsTypeLabel.setText(item.getReferCatalogName());
                    }

                }
            }
        }

        if (AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).list_icon_style == 1) {
            newsTypeLabel.setTextColor(Color.WHITE);
            if (shapeDrawable == null) {
                int size = getContext().getResources().getDimensionPixelSize(R.dimen.defaultloading_roundradius);
                shapeDrawable = generateRoundShapeDrawable(size, DefaultBgUtil.getTintColor(getContext()));
            }
            newsTypeLabel.setBackground(shapeDrawable);
        } else {
            Drawable drawable = ContextCompat.getDrawable(newsTypeLabel.getContext(), R.drawable.newstag_bgshape);
            int color = DefaultBgUtil.getTintColor(getContext());// Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(newsTypeLabel.getContext()).getTag_color());
            drawable = Utility.tintDrawable(DefaultBgUtil.getTintColor(getContext()), drawable);
            newsTypeLabel.setBackground(drawable);
            newsTypeLabel.setTextColor(color);
        }
    }

    public boolean needSetNewsTagLabel(int newsType) {
        int index = ArrayUtils.indexOf(TypeX.INSTANCE.getSpecialNewsTypeArr4Label(), newsType);
        return index >= 0;
    }

    private void dealComment(ArticleItem articleItem) {
        String comment = serializeCommentNum(articleItem.getCommentCount(), getContext(), articleItem);
        tvNewsComment.setText(comment);
        boolean showComment = articleItem.mShowSwitch != null && articleItem.mShowSwitch.allowShowComment;
/**
 * 是否显示评论
 */
        boolean isAllowComment = showComment && "1".equals(articleItem.getIsComment()) && !TextUtils.isEmpty(comment);
        boolean isShowInteractionCount = articleItem.mShowSwitch != null && articleItem.mShowSwitch.allowShowInteractionCount;
        //如果不显示那个点击评论和总量  就走原来的流程item.getInteractionCount()
        if (!isShowInteractionCount) {
            tvNewsComment.setVisibility(isAllowComment ? View.VISIBLE : View.GONE);
            if (isAllowComment){
                boolean cobot_temp = setInteractSpecialIcon(tvNewsComment,articleItem.getCommentCount()); 
                if(!cobot_temp){
                     tvNewsComment.setVisibility(View.VISIBLE);
                }
            }
                
        } else if (!setInteractSpecialIcon(tvNewsComment, articleItem.getInteractionCount()))//否则就显示评论text  不过设置值为
        {
            tvNewsComment.setVisibility(View.VISIBLE);
            tvNewsComment.setText(articleItem.getInteractionCount() + tvNewsComment.getResources().getString(R.string.interact_label));
            tvNewsComment.setBackgroundResource(R.drawable.interact_comment_rect);
        }
            }
    }

    private String serializeCommentNum(long num, Context mContext, ArticleItem item) {
        int max = mContext.getResources().getInteger(R.integer.tenthousands_commentnum);
        String commentStr = mContext.getResources().getString(R.string.commentstr);
        String tenthousandsStr = mContext.getResources().getString(R.string.tenthousands_en);
        String thousandsStr = mContext.getResources().getString(R.string.thousands_en);
        DecimalFormat df = new DecimalFormat("#.#");
        if (num >= max) {
            double value = num / (max * 1.0D);
//			num= num/max;
            //	if(AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).isAllowShowComment())
            if (item.mShowSwitch != null && item.mShowSwitch.allowShowComment)
                return df.format(value) + tenthousandsStr + commentStr;
        } else if (num >= (max / 10)) {
            double value = num / (max / 10.0D);
//			num= num/max;
            //    if (AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).isAllowShowComment())
            if (item.mShowSwitch != null && item.mShowSwitch.allowShowComment)
                return df.format(value) + thousandsStr + commentStr;
        } else if (num <= 0) {
            num = 0;
        }
        //  if (AppFactoryGlobalConfig.getAppServerConfigInfo(mContext).isAllowShowComment())
        if (item.mShowSwitch != null && item.mShowSwitch.allowShowComment)
            return num + commentStr;
        return "";
    }

    protected Drawable appfacSpecialIcon;

    protected boolean setInteractSpecialIcon(TextView textView, long interactCount) {
        boolean isRound = AppFactoryGlobalConfig.getAppServerConfigInfo(textView.getContext()).isRound();
        if (!isRound) {
            return false;
        }
        textView.setBackgroundColor(Color.TRANSPARENT);
        textView.setVisibility(View.VISIBLE);
        //不要删除前面的空格
        textView.setText(" " + interactCount);
        if (appfacSpecialIcon == null) {
            appfacSpecialIcon = ContextCompat.getDrawable(textView.getContext(), getInteractDrawableId()).getConstantState().newDrawable();
            int size = getInteractDrawableSize();
            appfacSpecialIcon.setBounds(0, 0, size, size);
        }
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setCompoundDrawablesRelative(appfacSpecialIcon, null, null, null);
        return true;
    }

    protected int getInteractDrawableSize() {
        return getContext().getResources().getDimensionPixelSize(R.dimen.dimen12);
    }

    protected @DrawableRes
    int getInteractDrawableId() {
        return R.drawable.common_comments;
    }
}
